/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.crane.webtemplate.dao;

import java.io.File;
import java.net.URL;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.*;
import org.hibernate.cfg.*;


/**
 *
 * @author CraneLeeon
 */
public class HibernateUtil {
    private static Log logger = LogFactory.getLog(HibernateUtil.class);
    private static SessionFactory sessionFactory;
    
    /**
     * Initial Hibernate SessionFactory
     * @param cfgFilePath path of hibernate cfg file
     * @param registerJMX JMX switch
     */
    public static void initial(String cfgFilePath,boolean registerJMX){
        try {
            sessionFactory = new Configuration().configure(cfgFilePath).buildSessionFactory();
            if(registerJMX)JmxAgent.getDefault(sessionFactory);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            logger.fatal("Initial SessionFactory creation failed.",ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * Initial Hibernate SessionFactory
     * @param cfgFile hibernate Configuration file
     * @param registerJMX JMX switch
     */
    public static void initial(File cfgFile,boolean registerJMX){
        try {
            sessionFactory = new Configuration().configure(cfgFile).buildSessionFactory();
            if(registerJMX)JmxAgent.getDefault(sessionFactory);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            logger.fatal("Initial SessionFactory creation failed.",ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * Initial Hibernate SessionFactory
     * @param cfgfileUrl url of hibernate cfg file
     * @param registerJMX JMX switch
     */
    public static void initial(URL cfgfileUrl,boolean registerJMX){
        try {
            sessionFactory = new Configuration().configure(cfgfileUrl).buildSessionFactory();
            if(registerJMX)JmxAgent.getDefault(sessionFactory);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            logger.fatal("Initial SessionFactory creation failed.",ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    /**
     * Initial Hibernate SessionFactory with the file hibernate.cfg.xml located on classes root dir
     * @param registerJMX JMX switch
     */
    public static void initial(boolean registerJMX){
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure().buildSessionFactory();
            if(registerJMX)JmxAgent.getDefault(sessionFactory);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            logger.fatal("Initial SessionFactory creation failed.",ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static Session openSession(){
        return getSessionFactory().openSession();
    }

    public static StatelessSession openStatelessSession(){
        return getSessionFactory().openStatelessSession();
    }

    public static Session getCurrentSession(){
        return getSessionFactory().getCurrentSession();
    }
    
    public static void commitTransaction() throws HibernateException {
        HibernateUtil.getCurrentSession().beginTransaction().commit();
    }
    
    public static void startTransaction() throws HibernateException {
        HibernateUtil.getCurrentSession().beginTransaction();
    }
    
    public static void rollbackTransaction() throws HibernateException {
        HibernateUtil.getCurrentSession().beginTransaction().rollback();
    }
}

